﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using REPORT.DAL;
using REPORT.DTO;
using System.Data.SqlClient;

namespace REPORT.GUI
{
    public partial class XuatHoaDon : DevExpress.XtraEditors.XtraForm
    {
        AutoCompleteStringCollection AutoKH = new AutoCompleteStringCollection();
        AutoCompleteStringCollection AutoNV = new AutoCompleteStringCollection();
        DAL_HOADON dalhd = new DAL_HOADON();
        DAL_KHACHHANG dalkh = new DAL_KHACHHANG();
        DAL_NGUOIDUNG dalnd = new DAL_NGUOIDUNG();
        DAL_SANPHAM dalsp = new DAL_SANPHAM();
        DAL_CHITIETHOADON dalcthd = new DAL_CHITIETHOADON();
        DTO_KHACHHANG dtokh = new DTO_KHACHHANG();
        DTO_HOADON dtohd = new DTO_HOADON();
        DTO_LOAISANPHAM dtoLSP = new DTO_LOAISANPHAM();
        DTO_CHITIETHOADON dtocthd = new DTO_CHITIETHOADON();
        DTO_SANPHAM dtosp = new DTO_SANPHAM();
        BindingSource bs = new BindingSource();
        int maKH, maND, maHD, maSP, maNDMoi, maKHMoi, maHDCu;
        
        public XuatHoaDon()
        {
            InitializeComponent();
        }

        private void XuatHoaDon_Load(object sender, EventArgs e)
        {
            AutoHoTenKhachHang();
            LoadLoaiSP();
            AutoHoTenNhanVien();
            LoadMaHD();
        }
        public void AutoHoTenNhanVien()
        {
            DataTable dt = new DataTable();
            dt = dalnd.AutoTenNV();
            foreach (DataRow row in dt.Rows)
            {
                AutoNV.Add(row[0].ToString());                
            }            
            txtHTNV.AutoCompleteMode = AutoCompleteMode.Suggest;
            txtHTNV.AutoCompleteSource = AutoCompleteSource.CustomSource;
            txtHTNV.AutoCompleteCustomSource = AutoNV;            
        }
        public void AutoHoTenKhachHang()
        {
            DataTable dt = new DataTable();
            dt = dalkh.AutoTenKH();
            foreach (DataRow row in dt.Rows)
            {
                AutoKH.Add(row[0].ToString());                
            }
            txtHTKH.AutoCompleteMode = AutoCompleteMode.Suggest;
            txtHTKH.AutoCompleteSource = AutoCompleteSource.CustomSource;
            txtHTKH.AutoCompleteCustomSource = AutoKH;
            
        }

        private void txtHTKH_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                SqlDataReader dReader;
                dReader = dalkh.LayMaKH(txtHTKH.Text);
                if (dReader.HasRows == true)
                {
                    while (dReader.Read())
                    {
                        maKH = Convert.ToInt32((dReader["ma_khach_hang"].ToString()));
                        txtDC.Text = dReader["dia_chi"].ToString();
                        txtSDT.Text = dReader["so_dien_thoai"].ToString();
                    }
                }
                lblNguoiMua.Text = txtHTKH.Text;
                dReader.Close();
            }
            
        }

        private void txtHTNV_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                SqlDataReader dReader;
                dReader = dalnd.LayMaNV(txtHTNV.Text);
                if (dReader.HasRows == true)
                {
                    while (dReader.Read())
                    {
                        maND = Convert.ToInt32((dReader["ma_nguoi_dung"].ToString()));
                    }
                }             
                lblNguoiBan.Text = txtHTNV.Text;               
                dReader.Close();
            }
            
        }
        public void LayMaKH()
        {
            SqlDataReader dReader;
            dReader = dalkh.LayMaKH(txtHTKH.Text);
            if (dReader.HasRows == true)
            {
                while (dReader.Read())
                {
                    maKHMoi = Convert.ToInt32((dReader["ma_khach_hang"].ToString()));
                    txtDC.Text = dReader["dia_chi"].ToString();
                    txtSDT.Text = dReader["so_dien_thoai"].ToString();
                }
            }
            lblNguoiMua.Text = txtHTKH.Text;
            dReader.Close();
        }
        public void LayMaNV()
        {
            SqlDataReader dReader;
            dReader = dalnd.LayMaNV(txtHTNV.Text);
            if (dReader.HasRows == true)
            {
                while (dReader.Read())
                {
                    maNDMoi = Convert.ToInt32((dReader["ma_nguoi_dung"].ToString()));
                }
            }
            lblNguoiBan.Text = txtHTNV.Text;
            dReader.Close();
        }
        public void LoadLoaiSP()
        {
            DataTable dt = new DataTable();
            dt = dalsp.LoadLoaiSP();
            cbxLoaiHang.DataSource = dt;
            cbxLoaiHang.DisplayMember = "ten_loai_san_pham";
            cbxLoaiHang.ValueMember = "ma_loai_san_pham";
            cbxLoaiHang.AutoCompleteMode = AutoCompleteMode.Suggest;
            cbxLoaiHang.AutoCompleteSource = AutoCompleteSource.ListItems;
        }
        public void LoadMaHD()
        {
            DataTable dt1 = new DataTable();
            dt1 = dalhd.LoadMaHD();
            cbxSoHD.DataSource = dt1;
            cbxSoHD.DisplayMember = "ma_hoa_don";
            cbxSoHD.ValueMember = "ma_hoa_don";
        }
        private void cbxLoaiHang_SelectedIndexChanged(object sender, EventArgs e)
        {
            //try
            //{
            //    DataTable dt = new DataTable();
            //    dt = dalsp.LoadSPTheoLoai(Convert.ToInt32(cbxLoaiHang.SelectedValue.ToString()));
            //    dtgSanPham.DataSource = dt;
            //}
            //catch 
            //{

            //}
            
        }

        private void sbtnTaoHDMoi_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtHTNV.Text == "" || txtHTKH.Text == "")
                {
                    MessageBox.Show("Vui lòng điền tên nhân viên và khách hàng");
                    return;
                }
                else
                {
                    LayMaKH();
                    LayMaNV();
                    dtohd.MaKhachHang = maKHMoi;
                    dtohd.MaNguoiDung = maNDMoi;
                    dtohd.NgayLap = Convert.ToDateTime(dtpNgayLap.Value.ToShortDateString());
                    if (dalhd.ThemHD(dtohd) > 0)
                    {
                        DataTable dt = new DataTable();
                        dt = dalhd.IdMax();
                        maHD = Convert.ToInt32(dt.Rows[0]["ma_hoa_don"].ToString());
                        cbxSoHD.Text = maHD.ToString();
                    }
                }
            }
            catch 
            {
                MessageBox.Show("Hóa đơn này đã tồn tại, vui lòng cập nhật lại hàng");
            }
            
        }

        private void sbtnThemVaoHD_Click(object sender, EventArgs e)
        {
            
            try
            {
                if (dalcthd.KiemTraTonTaiMaHD(maHD) == false)
                {
                    dtocthd.MaHoaDon = maHD;
                    dtocthd.MaSanPham = Convert.ToInt32(dtgSanPham.CurrentRow.Cells["masp"].Value);
                    maSP = Convert.ToInt32(dtgSanPham.CurrentRow.Cells["masp"].Value);
                    dtocthd.SoLuong = 1;
                    dtocthd.DonGia = float.Parse(dtgSanPham.CurrentRow.Cells["dongiamua"].Value.ToString());
                    dtocthd.DonViTinh = dtgSanPham.CurrentRow.Cells["dvt"].Value.ToString();
                    dtosp.SoLuong = dtocthd.SoLuong;
                    dtosp.MaSanPham = dtocthd.MaSanPham;
                    if (dalcthd.ThemCTHD(dtocthd) > 0 && dalsp.UpdateSoLuong(dtosp) > 0)
                    {
                        double tongtien = 0;
                        DataTable dt1 = new DataTable();
                        dt1 = dalcthd.MaHD(maHD);
                        bs.DataSource = dt1;
                        dtgHoaDon.DataSource = dt1;
                        DataTable dt = new DataTable();
                        dt = dalsp.LoadSPTheoLoai(Convert.ToInt32(cbxLoaiHang.SelectedValue.ToString()));
                        dtgSanPham.DataSource = dt;
                        for (int i = 0; i < dtgHoaDon.Rows.Count - 1; i++)
                        {
                            tongtien += Convert.ToDouble(dtgHoaDon["thanhtien", i].Value.ToString());
                        }
                        lblTongtien.Text = tongtien.ToString("#,###" + " VNĐ");
                        lblBangchu.Text = ChuyenSo(tongtien.ToString()) + "đồng";
                    }
                    else
                    {
                        MessageBox.Show("Vui lòng cập nhật lại số lượng");
                    }
                }
                else
                {
                    dtocthd.MaHoaDon = Convert.ToInt32(cbxSoHD.Text);
                    dtocthd.MaSanPham = Convert.ToInt32(dtgSanPham.CurrentRow.Cells["masp"].Value);
                    maSP = Convert.ToInt32(dtgSanPham.CurrentRow.Cells["masp"].Value);
                    dtocthd.SoLuong = 1;
                    dtocthd.DonGia = float.Parse(dtgSanPham.CurrentRow.Cells["dongiamua"].Value.ToString());
                    dtocthd.DonViTinh = dtgSanPham.CurrentRow.Cells["dvt"].Value.ToString();
                    dtosp.SoLuong = dtocthd.SoLuong;
                    dtosp.MaSanPham = dtocthd.MaSanPham;
                    if (dalcthd.ThemCTHDCu(dtocthd) > 0 && dalsp.UpdateSoLuong(dtosp) > 0)
                    {
                        double tongtien = 0;
                        DataTable dt1 = new DataTable();
                        dt1 = dalcthd.MaHD(Convert.ToInt32(cbxSoHD.Text));
                        bs.DataSource = dt1;
                        dtgHoaDon.DataSource = dt1;
                        DataTable dt = new DataTable();
                        dt = dalsp.LoadSPTheoLoai(Convert.ToInt32(cbxLoaiHang.SelectedValue.ToString()));
                        dtgSanPham.DataSource = dt;
                        for (int i = 0; i < dtgHoaDon.Rows.Count - 1; i++)
                        {
                            tongtien += Convert.ToDouble(dtgHoaDon["thanhtien", i].Value.ToString());
                        }
                        lblTongtien.Text = tongtien.ToString("#,###" + " VNĐ");
                        lblBangchu.Text = ChuyenSo(tongtien.ToString()) + "đồng";
                    }
                    else
                    {
                        MessageBox.Show("Vui lòng cập nhật lại số lượng");
                    }
                }
                
            }
            catch 
            {
                MessageBox.Show("Hàng này đã có, Vui lòng cập nhật lại số lượng");
            }
            

        }

        private void dtgHoaDon_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            dtocthd.MaHoaDon = Convert.ToInt32(dtgHoaDon.CurrentRow.Cells["mahd_cthd"].Value);
            dtocthd.MaSanPham = Convert.ToInt32(dtgHoaDon.CurrentRow.Cells["masp_cthd"].Value);
            dtocthd.SoLuong = Convert.ToInt32(dtgHoaDon.CurrentRow.Cells["soluong"].Value);
            dtosp.SoLuong = dtocthd.SoLuong;
            dtosp.MaSanPham = dtocthd.MaSanPham;
           // dtgHoaDon.CancelEdit();
            try
            {
                if (dalcthd.UpdateSoLuong(dtocthd) > 0 && dalsp.UpdateSoLuong(dtosp) > 0)
                {
                    MessageBox.Show("Update cho cthd");
                
                        double tongtien = 0;
                        DataTable dt1 = new DataTable();
                        dt1 = dalcthd.MaHD(dtocthd.MaHoaDon);
                        bs.DataSource = dt1;
                        dtgHoaDon.DataSource = dt1;
                        DataTable dt = new DataTable();
                        dt = dalsp.LoadSPTheoLoai(Convert.ToInt32(cbxLoaiHang.SelectedValue.ToString()));
                        dtgSanPham.DataSource = dt;
                        for (int i = 0; i < dtgHoaDon.Rows.Count-1; i++)
                        {
                            tongtien += Convert.ToDouble(dtgHoaDon["thanhtien", i].Value.ToString());
                        }
                        lblTongtien.Text = tongtien.ToString("#,###" + " VNĐ");
                        lblBangchu.Text = ChuyenSo(tongtien.ToString()) + " đồng";        
             
                }
            }
            catch
            {

            }
        }

        private void sbtnXoaKhoiHD_Click(object sender, EventArgs e)
        {
            dtocthd.MaHoaDon = Convert.ToInt32(dtgHoaDon.CurrentRow.Cells["mahd_cthd"].Value);
            dtocthd.MaSanPham = Convert.ToInt32(dtgHoaDon.CurrentRow.Cells["masp_cthd"].Value);
            dtocthd.SoLuong = Convert.ToInt32(dtgHoaDon.CurrentRow.Cells["soluong"].Value);
            dtosp.SoLuong = dtocthd.SoLuong;
            dtosp.MaSanPham = dtocthd.MaSanPham;
            if (dalcthd.XoaHangCTHD(dtocthd) > 0 && dalsp.UpdateSoLuongKhiXoaKhoiCTHD(dtosp)>0)
            {
                double tongtien = 0;
                DataTable dt1 = new DataTable();
                dt1 = dalcthd.MaHD(dtocthd.MaHoaDon);
                bs.DataSource = dt1;
                dtgHoaDon.DataSource = dt1;
                DataTable dt = new DataTable();
                dt = dalsp.LoadSPTheoLoai(Convert.ToInt32(cbxLoaiHang.SelectedValue.ToString()));
                dtgSanPham.DataSource = dt;
                for (int i = 0; i < dtgHoaDon.Rows.Count-1; i++)
                {
                    tongtien += Convert.ToDouble(dtgHoaDon["thanhtien", i].Value.ToString());
                }
                lblTongtien.Text = tongtien.ToString("#,###" + " VNĐ");
                lblBangchu.Text = ChuyenSo(tongtien.ToString()) + " đồng";
            }
        }

        private void cbxSoHD_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            try
            {
                double tongtien = 0;
                DataTable dt = new DataTable();
                dt = dalcthd.LoadTheoMaHD(Convert.ToInt32(cbxSoHD.Text));
                dtgHoaDon.DataSource = dt;
                DataTable dt1 = new DataTable();
                dt1 = dalhd.ThongTinTheoHDDuocChon(Convert.ToInt32(cbxSoHD.Text));
                txtHTNV.Text = dt1.Rows[0]["ho_ten"].ToString();
                lblNguoiBan.Text = dt1.Rows[0]["ho_ten"].ToString();
                txtHTKH.Text = dt1.Rows[0]["ten_khach_hang"].ToString();
                lblNguoiMua.Text = dt1.Rows[0]["ten_khach_hang"].ToString();
                txtDC.Text = dt1.Rows[0]["dia_chi"].ToString();
                txtSDT.Text = dt1.Rows[0]["so_dien_thoai"].ToString();
                for (int i = 0; i < dtgHoaDon.Rows.Count - 1; i++)
                {
                    tongtien += Convert.ToDouble(dtgHoaDon["thanhtien", i].Value.ToString());
                }
                lblTongtien.Text = tongtien.ToString("#,###" + " VNĐ");
                lblBangchu.Text = ChuyenSo(tongtien.ToString()) + " đồng";
            }
            catch 
            {

            }
            
        }

        private void dtpNgayLap_ValueChanged(object sender, EventArgs e)
        {            
            try
            {
                dtohd.NgayLap = Convert.ToDateTime(dtpNgayLap.Value.ToShortDateString());
                dtohd.MaHoaDon = Convert.ToInt32(Convert.ToInt32(cbxSoHD.Text));
                dalhd.SuaNgayLap(dtohd);
            }
            catch 
            {

            }
        }
        ////////////Text chuyen so sang chu////////////
        private string ChuyenSo(string number)
        {
            string[] dv = { "", "mươi", "trăm", "nghìn", "triệu", "tỷ" };
            string[] cs = { "không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín" };
            string doc;
            int i, j, k, n, len, found, ddv, rd;

            len = number.Length;
            number += "ss";
            doc = "";
            found = 0;
            ddv = 0;
            rd = 0;

            i = 0;
            while (i < len)
            {
                //So chu so o hang dang duyet
                n = (len - i + 2) % 3 + 1;

                //Kiem tra so 0
                found = 0;
                for (j = 0; j < n; j++)
                {
                    if (number[i + j] != '0')
                    {
                        found = 1;
                        break;
                    }
                }

                //Duyet n chu so
                if (found == 1)
                {
                    rd = 1;
                    for (j = 0; j < n; j++)
                    {
                        ddv = 1;
                        switch (number[i + j])
                        {
                            case '0':
                                if (n - j == 3) doc += cs[0] + " ";
                                if (n - j == 2)
                                {
                                    if (number[i + j + 1] != '0') doc += "nobiet ";
                                    ddv = 0;
                                }
                                break;
                            case '1':
                                if (n - j == 3) doc += cs[1] + " ";
                                if (n - j == 2)
                                {
                                    doc += "mười ";
                                    ddv = 0;
                                }
                                if (n - j == 1)
                                {
                                    if (i + j == 0) k = 0;
                                    else k = i + j - 1;

                                    if (number[k] != '1' && number[k] != '0')
                                        doc += "một ";
                                    else
                                        doc += cs[1] + " ";
                                }
                                break;
                            case '5':
                                if (i + j == len - 1)
                                    doc += "năm ";
                                else
                                    doc += cs[5] + " ";
                                break;
                            default:
                                doc += cs[(int)number[i + j] - 48] + " ";
                                break;
                        }

                        //Doc don vi nho
                        if (ddv == 1)
                        {
                            doc += dv[n - j - 1] + " ";
                        }
                    }
                }


                //Doc don vi lon
                if (len - i - n > 0)
                {
                    if ((len - i - n) % 9 == 0)
                    {
                        if (rd == 1)
                            for (k = 0; k < (len - i - n) / 9; k++)
                                doc += "tỷ ";
                        rd = 0;
                    }
                    else
                        if (found != 0) doc += dv[((len - i - n + 1) % 9) / 3 + 2] + " ";
                }

                i += n;
            }

            if (len == 1)
                if (number[0] == '0' || number[0] == '5') return cs[(int)number[0] - 48];

            return doc;
        }

        private void sbtnXoaHD_Click(object sender, EventArgs e)
        {

        }

        private void sbtnInHD_Click(object sender, EventArgs e)
        {
            DataSet ds1 = new DataSet();
            DataRow dr;
            //try
            //{
                ds1.Tables.Add();
                for (int i = 0; i < dtgHoaDon.Columns.Count - 2; i++)
                {
                    ds1.Tables[0].Columns.Add(dtgHoaDon.Columns[i].HeaderText);
                }
                for (int i = 0; i < dtgHoaDon.Rows.Count - 1; i++)
                {
                    dr = ds1.Tables[0].NewRow();
                    for (int j = 0; j < dtgHoaDon.Columns.Count-2; j++)
                    {
                        dr[j] = dtgHoaDon.Rows[i].Cells[j].Value;
                    }
                    ds1.Tables[0].Rows.Add(dr);
                }
                XtraRptHoaDon xtrpt = new XtraRptHoaDon();
                xtrpt.ds = ds1;
                FrmXtraReport frm = new FrmXtraReport();                
                frm.xuathd = ds1;
                frm.HoTenKH = lblNguoiMua.Text;
                frm.HoTenNguoiBan = lblNguoiBan.Text;
                frm.SDT = txtSDT.Text;
                frm.DiaChi = txtDC.Text;
                frm.SoHD = cbxSoHD.Text;
                frm.TongTienBangChu = lblBangchu.Text;
                frm.TongTienBangSo = lblTongtien.Text;
                frm.NgayLap = "Ngày " + dtpNgayLap.Value.Day+" Tháng "+ dtpNgayLap.Value.Month+" Năm "+ dtpNgayLap.Value.Year;
                frm.Show();
                //}

            //}
            //catch
            //{

            //}
        }

        private void cbxLoaiHang_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = dalsp.LoadSPTheoLoai(Convert.ToInt32(cbxLoaiHang.SelectedValue.ToString()));
                dtgSanPham.DataSource = dt;
            }
            catch
            {

            }
        }

        private void sbtnHuyHD_Click(object sender, EventArgs e)
        {

        }
        //////////////end//////////////////////////////
               
    }
}